/**
 * 私信路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 处理私信相关的API请求，包括消息发送、接收、查询、删除、标记已读等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const messagesAPI = require('../../libs/messages-api');

/**
 * 发送私信
 * POST /messages/send
 * @body {number} senderId - 发送者ID
 * @body {number} receiverId - 接收者ID
 * @body {string} content - 消息内容
 * @body {string} [messageType='text'] - 消息类型
 * @body {Array} [attachments=[]] - 附件列表
 */
router.post('/send', async (req, res) => {
    try {
        const { senderId, receiverId, content, messageType = 'text', attachments = [] } = req.body;
        
        // 参数验证
        if (!senderId || !receiverId || !content) {
            return res.status(400).json({
                success: false,
                message: '发送者ID、接收者ID和消息内容不能为空'
            });
        }
        
        if (isNaN(senderId) || isNaN(receiverId)) {
            return res.status(400).json({
                success: false,
                message: '发送者ID和接收者ID必须是数字'
            });
        }
        
        if (typeof content !== 'string' || content.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '消息内容必须是非空字符串'
            });
        }
        
        if (content.trim().length > 1000) {
            return res.status(400).json({
                success: false,
                message: '消息内容不能超过1000个字符'
            });
        }
        
        if (!['text', 'image', 'video', 'file'].includes(messageType)) {
            return res.status(400).json({
                success: false,
                message: '消息类型必须是text、image、video或file'
            });
        }
        
        if (!Array.isArray(attachments)) {
            return res.status(400).json({
                success: false,
                message: '附件列表必须是数组'
            });
        }
        
        const message = await messagesAPI.sendMessage({
            senderId: parseInt(senderId),
            receiverId: parseInt(receiverId),
            content: content.trim(),
            messageType,
            attachments,
            ip: req.ip || req.connection.remoteAddress || ''
        });
        
        res.json({
            success: true,
            message: '发送私信成功',
            data: message
        });
    } catch (error) {
        console.error('发送私信失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '发送私信失败'
        });
    }
});

/**
 * 获取会话列表
 * GET /messages/conversations/:userId
 * @param {number} userId - 用户ID
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/conversations/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '页码和每页数量必须是数字'
            });
        }
        
        const result = await messagesAPI.getConversations({
            userId: parseInt(userId),
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('获取会话列表失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取会话列表失败'
        });
    }
});

/**
 * 获取会话消息列表
 * GET /messages/conversation/:conversationId/:userId
 * @param {string} conversationId - 会话ID
 * @param {number} userId - 用户ID
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/conversation/:conversationId/:userId', async (req, res) => {
    try {
        const { conversationId, userId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!conversationId || !userId) {
            return res.status(400).json({
                success: false,
                message: '会话ID和用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '页码和每页数量必须是数字'
            });
        }
        
        // 验证会话ID格式
        if (!/^\d+_\d+$/.test(conversationId)) {
            return res.status(400).json({
                success: false,
                message: '会话ID格式不正确'
            });
        }
        
        const result = await messagesAPI.getConversationMessages({
            conversationId,
            userId: parseInt(userId),
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('获取会话消息列表失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取会话消息列表失败'
        });
    }
});

/**
 * 获取消息详情
 * GET /messages/detail/:messageId/:userId
 * @param {number} messageId - 消息ID
 * @param {number} userId - 用户ID
 */
router.get('/detail/:messageId/:userId', async (req, res) => {
    try {
        const { messageId, userId } = req.params;
        
        // 参数验证
        if (!messageId || !userId) {
            return res.status(400).json({
                success: false,
                message: '消息ID和用户ID不能为空'
            });
        }
        
        if (isNaN(messageId) || isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '消息ID和用户ID必须是数字'
            });
        }
        
        const message = await messagesAPI.getMessageDetail(
            parseInt(messageId),
            parseInt(userId)
        );
        
        if (!message) {
            return res.status(404).json({
                success: false,
                message: '消息不存在'
            });
        }
        
        res.json({
            success: true,
            data: message
        });
    } catch (error) {
        console.error('获取消息详情失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取消息详情失败'
        });
    }
});

/**
 * 标记消息为已读
 * PUT /messages/mark-read
 * @body {string} [conversationId] - 会话ID
 * @body {number} userId - 用户ID
 * @body {number[]} [messageIds] - 消息ID数组
 */
router.put('/mark-read', async (req, res) => {
    try {
        const { conversationId, userId, messageIds } = req.body;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (!conversationId && !messageIds) {
            return res.status(400).json({
                success: false,
                message: '会话ID或消息ID数组不能同时为空'
            });
        }
        
        if (conversationId && !/^\d+_\d+$/.test(conversationId)) {
            return res.status(400).json({
                success: false,
                message: '会话ID格式不正确'
            });
        }
        
        if (messageIds && (!Array.isArray(messageIds) || messageIds.some(id => isNaN(id)))) {
            return res.status(400).json({
                success: false,
                message: '消息ID数组格式不正确'
            });
        }
        
        const result = await messagesAPI.markAsRead({
            conversationId,
            userId: parseInt(userId),
            messageIds: messageIds ? messageIds.map(id => parseInt(id)) : undefined
        });
        
        res.json({
            success: true,
            message: '标记已读成功',
            data: result
        });
    } catch (error) {
        console.error('标记消息为已读失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '标记消息为已读失败'
        });
    }
});

/**
 * 删除消息
 * DELETE /messages/delete/:messageId/:userId
 * @param {number} messageId - 消息ID
 * @param {number} userId - 用户ID
 */
router.delete('/delete/:messageId/:userId', async (req, res) => {
    try {
        const { messageId, userId } = req.params;
        
        // 参数验证
        if (!messageId || !userId) {
            return res.status(400).json({
                success: false,
                message: '消息ID和用户ID不能为空'
            });
        }
        
        if (isNaN(messageId) || isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '消息ID和用户ID必须是数字'
            });
        }
        
        const result = await messagesAPI.deleteMessage(
            parseInt(messageId),
            parseInt(userId)
        );
        
        res.json({
            success: true,
            message: '删除消息成功',
            data: result
        });
    } catch (error) {
        console.error('删除消息失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除消息失败'
        });
    }
});

/**
 * 删除会话
 * DELETE /messages/conversation/:conversationId/:userId
 * @param {string} conversationId - 会话ID
 * @param {number} userId - 用户ID
 */
router.delete('/conversation/:conversationId/:userId', async (req, res) => {
    try {
        const { conversationId, userId } = req.params;
        
        // 参数验证
        if (!conversationId || !userId) {
            return res.status(400).json({
                success: false,
                message: '会话ID和用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (!/^\d+_\d+$/.test(conversationId)) {
            return res.status(400).json({
                success: false,
                message: '会话ID格式不正确'
            });
        }
        
        const result = await messagesAPI.deleteConversation(
            conversationId,
            parseInt(userId)
        );
        
        res.json({
            success: true,
            message: '删除会话成功',
            data: result
        });
    } catch (error) {
        console.error('删除会话失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除会话失败'
        });
    }
});

/**
 * 获取未读消息数量
 * GET /messages/unread-count/:userId
 * @param {number} userId - 用户ID
 */
router.get('/unread-count/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        const count = await messagesAPI.getUnreadCount(parseInt(userId));
        
        res.json({
            success: true,
            data: { unreadCount: count }
        });
    } catch (error) {
        console.error('获取未读消息数量失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取未读消息数量失败'
        });
    }
});

/**
 * 搜索消息
 * GET /messages/search/:userId
 * @param {number} userId - 用户ID
 * @query {string} keyword - 搜索关键词
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/search/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { keyword, page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (!keyword || typeof keyword !== 'string' || keyword.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }
        
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '页码和每页数量必须是数字'
            });
        }
        
        const result = await messagesAPI.searchMessages({
            userId: parseInt(userId),
            keyword: keyword.trim(),
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('搜索消息失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '搜索消息失败'
        });
    }
});

/**
 * 获取消息统计
 * GET /messages/stats/:userId
 * @param {number} userId - 用户ID
 */
router.get('/stats/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        const stats = await messagesAPI.getMessageStats(parseInt(userId));
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取消息统计失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取消息统计失败'
        });
    }
});

/**
 * 生成会话ID
 * POST /messages/generate-conversation-id
 * @body {number} userId1 - 用户1 ID
 * @body {number} userId2 - 用户2 ID
 */
router.post('/generate-conversation-id', async (req, res) => {
    try {
        const { userId1, userId2 } = req.body;
        
        // 参数验证
        if (!userId1 || !userId2) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId1) || isNaN(userId2)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (userId1 === userId2) {
            return res.status(400).json({
                success: false,
                message: '不能与自己创建会话'
            });
        }
        
        const conversationId = messagesAPI.generateConversationId(
            parseInt(userId1),
            parseInt(userId2)
        );
        
        res.json({
            success: true,
            data: { conversationId }
        });
    } catch (error) {
        console.error('生成会话ID失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '生成会话ID失败'
        });
    }
});

module.exports = router;